package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.sercice.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService service;

    //添加菜品分类
    @PostMapping
    public R add(@RequestBody Category category) {
        service.save(category);
        return R.success("添加成功");
    }

    //菜品分页查询
    @GetMapping("/page")
    public R pageFind(Integer page, Integer pageSize) {
        Page pageInfo = new Page<>();
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        wrapper.orderByAsc(Category::getSort);

        service.page(pageInfo, wrapper);

        return R.success(pageInfo);
    }

    //删除
    @DeleteMapping
    public R del(Long id) {
        log.info("删除分类，id为：{}", id);
        service.remove(id);
        return R.success("删除成功");
    }

    //修改
    @PutMapping
    public R update(@RequestBody Category category) {
        log.info("修改分类信息：{}", category);
        service.updateById(category);
        return R.success("修改成功");
    }




    //根据条件  查询分类数据
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //创建条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加条件
        wrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //添加排序条件  先按照分类排序 相同的话就再按照修改时间排序
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = service.list(wrapper);
        return R.success(list);

    }

}
